<template>
  <div class="el-upload-model">
    <el-upload
      ref="upload"
      class="el-avatar-uploader"
      action="#"
      :multiple="multiple"
      :show-file-list="false"
      :http-request="handleUploadImg"
      :on-success="handleAvatarSuccess"
      list-type="picture-card"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="pictureUrl" src="@/assets/pdf.jpg" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>

    <div class="el-progress-grid"><el-progress v-if="progressFlag" class="el-progressbar" type="circle" color="#67c23a" :percentage="progressPercent" /></div>
  </div>
</template>
<script>
import { ossHost, aliyunOssApi } from '@/api/aliyun';
import axios from 'axios';

export default {
  name: 'UploadPdf',
  props: {
    pictureUrl: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      imageUrl: '',
      progressFlag: false,
      progressPercent: 0,
      ossHost: ossHost
    };
  },
  methods: {
    // 截取上传文件后缀
    getSuffix(filename) {
      let pos = filename.lastIndexOf('.');
      let suffix = '';
      if (pos !== -1) suffix = filename.substring(pos);
      return suffix;
    },
    // 生成随机数
    randomString(len) {
      len = len || 32;
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
      const maxPos = chars.length;
      let pwd = '';
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    beforeAvatarUpload(file) {
      const isPDF = file.type === 'application/pdf';
      // const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isPDF) {
        this.$message.error('上传的文件只能是PDF格式!');
      }

      return isPDF;
    },
    handleUploadImg(file) {
      aliyunOssApi('internal')
        .then(res => {
          if (res.code === 0) {
            let picName = this.randomString(10) + this.getSuffix(file.file.name);
            let keyValue = res.data.dir + picName;
            // 注意formData里append添加的键的大小写
            let formData = new FormData();
            formData.append('name', file.file.name); // 文件名称
            formData.append('key', keyValue); // 存储在oss的文件路径
            formData.append('OSSAccessKeyId', res.data.accessid); // accessKeyId
            formData.append('policy', res.data.policy); // policy
            formData.append('Signature', res.data.signature); // 签名
            formData.append('success_action_status', 200);
            formData.append('file', file.file, file.file.name); // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可

            this.progressFlag = true;
            return new Promise((resolve, reject) => {
              axios
                .post(this.ossHost, formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  },
                  // 上传进度
                  onUploadProgress: progressEvent => {
                    this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total);
                  }
                })
                .then(rep => {
                  if (rep.status === 200) {
                    this.imageUrl = this.ossHost + keyValue;
                    this.$emit('uploadSuccess', this.ossHost + keyValue);
                    if (this.progressPercent >= 100) {
                      this.progressFlag = false;
                      setTimeout(() => {
                        this.progressPercent = 0;
                      }, 1000);
                    }
                    this.$message.success('PDF文件上传成功');
                  }
                  resolve(rep);
                })
                .catch(err => {
                  reject(err);
                });
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleRemove(file) {
      this.$refs.upload.abort();
      this.$message({
        message: '成功移除' + file.name,
        type: 'success'
      });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    }
  }
};
</script>

<style scoped>
.avatar {
  width: 146px;
  height: 146px;
}
</style>
